//
//  TableEnable.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/5/24.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import Then
import RxSwift
import RxDataSources
import CooperSwift

private struct AssociateKeys {
    static var table: Void?
    // 也可以直接这样写
    // static var disablePopGesture = "disablePopGesture"
}

// MARK: - table enable
protocol TableEnableProtocol : BindKeyProtocol { }

// MARK: - table view
extension TableEnableProtocol {
    
    var tableView: UITableView {
        get {
            return associatedObject(forKey: &AssociateKeys.table, default: tableV(), ploicy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        set {
            objc_setAssociatedObject(self, &AssociateKeys.table, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    @discardableResult
    private func tableV() -> UITableView {
        tableView = UITableView.init().then {
            $0.backgroundColor = .white
            $0.estimatedRowHeight = 44

            $0.tableFooterView = UIView.init();
            $0.separatorStyle = .none;

            $0.showsVerticalScrollIndicator = false;
            $0.showsHorizontalScrollIndicator = false;
        }
        return tableView
    }
    
    
}

// MARK: - table for view controller
extension TableEnableProtocol where Self : UIViewController {
    
    func configTable(_ edges: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -Screen.bottomBarHeight, right: 0)) {
        bgColor(.white)
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(view).inset(edges)
        }
    }
    
    func bindVM(_ vm: TableViewModelProtocol, bag: DisposeBag) {
        
        let tv = tableView
        let dataSource: RxTableViewSectionedReloadDataSource = vm.configDataSource()
        
        vm.sectionsSubject.throttle(.milliseconds(300), latest: true, scheduler: MainScheduler.instance).bind(to: tv.rx.items(dataSource: dataSource)).disposed(by: bag)
        
        vm.holder()
        
        vm.bindKey(bag)
        
        vm.configServicBlock { [weak self] service in
            switch service {
            case .controller:
                return self
            
            case .table:
                return self?.tableView
                
            case .view:
                return self?.view
            }
            
        }
        
        tv.rx.setDelegate(vm).disposed(by: bag)
        
    }
    
}
